package com.jsbs.iam.user.service.impl;

import com.jsbs.iam.common.core.utils.StringUtils;
import com.jsbs.iam.user.entity.IamPostOrgRelation;
import com.jsbs.iam.user.mapper.PostOrgRelationMapper;
import com.jsbs.iam.user.param.PostOrgDto;
import com.jsbs.iam.user.param.PostOrgParam;
import com.jsbs.iam.user.service.PostOrgRelationService;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class PostOrgRelationServiceImpl implements PostOrgRelationService {
    @Autowired
    private PostOrgRelationMapper postOrgRelationMapper;

    @Override
    public void syncPostOrgInfo(PostOrgParam postOrgParam) {
        if (CollectionUtils.isEmpty(postOrgParam.getPostOrgList())) {
            return;
        }
        // 新增列表
        List<IamPostOrgRelation> postOrgRelations = new ArrayList<>();
        // 更新列表
        List<IamPostOrgRelation> updateList = new ArrayList<>();
        // 有效数据
        List<PostOrgDto> enableList = postOrgParam.getPostOrgList().stream().filter(item -> StringUtils.isNotEmpty(item.getOrgCode()) && StringUtils.isNotEmpty(item.getPostId())).collect(Collectors.toList());
        enableList.forEach(item -> {
            IamPostOrgRelation relation = new IamPostOrgRelation();
            BeanUtils.copyProperties(item, relation);
            // 归属租户
            relation.setCompanyCode(postOrgParam.getCompanyCode());
            // 归属组织类型
            relation.setOrgTypeCode(postOrgParam.getDataSource());
            // 判断是否已存在 或 失效的直接更新
            if (0 == item.getStatus() || postOrgRelationMapper.countByOrgPostCode(postOrgParam.getCompanyCode(), postOrgParam.getDataSource(), item.getOrgCode(), item.getPostId()) > 0) {
                updateList.add(relation);
            } else {
                postOrgRelations.add(relation);
            }
        });
        // 批量新增
        if (CollectionUtils.isNotEmpty(postOrgRelations)) {
            postOrgRelationMapper.batchInsert(postOrgRelations);
        }
        // 批量更新
        if (CollectionUtils.isNotEmpty(updateList)) {
            postOrgRelationMapper.batchUpdate(updateList);
        }
    }
}
